// 临时装置受力分析
import React, { useState, useEffect, useMemo, useCallback } from "react";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/components/ui/use-toast";
import {
  Save,
  Calculator,
  AlertTriangle,
  MoveRight,
  Anchor,
  Pilcrow,
  Combine,
  Boxes,
  Loader2,
} from "lucide-react";
import { TooltipProvider } from "@/components/ui/tooltip";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
// 修复：直接从各自的实体文件导入
import { PoleSpecAPI } from "@/api/PoleSpec";
import { AnchorSpecAPI } from "@/api/AnchorSpec";
import FormulaDisplay from "../FormulaDisplay";
import FieldWithTooltip from "../FieldWithTooltip";
export default function TemporaryStructureCalculator({ scheme, onUpdate }) {
  const { toast } = useToast();
  const [poleSpecs, setPoleSpecs] = useState([]);
  const [anchorSpecs, setAnchorSpecs] = useState([]);
  const [isLoadingSpecs, setIsLoadingSpecs] = useState(true);
  console.log(scheme, "scheme.inputParametersscheme.inputParameters");

  const bearingCableMaxTensionKN = useMemo(() => {
    const results = scheme.bearingCableCalculationResults;
    // 明确从承载索计算结果的“事故动载”工况中获取最大张力
    if (
      results &&
      results.data &&
      results.data.workConditions &&
      results.data.workConditions.accidentDynamic
    ) {
      // 从承载索计算结果的事故动载工况中获取最大张力（kN）
      return results.data.workConditions.accidentDynamic.maxTension; // 单位：kN
    } else if (
      scheme.inputParameters?.carryingCableMaxTension != null &&
      scheme.inputParameters.carryingCableMaxTension !== ""
    ) {
      return parseFloat(scheme.inputParameters.carryingCableMaxTension) || 0;
    }
    // 如果没有找到有效值，则返回0
    return 0; // 如果数据不存在则返回0
  }, [scheme.bearingCableCalculationResults, scheme.inputParameters]);

  const autoCalculatedVerticalLoadOnBeam = useMemo(() => {
    const betaRad = (45 * Math.PI) / 180;
    return 3 * bearingCableMaxTensionKN * Math.sin(betaRad);
  }, [bearingCableMaxTensionKN]);

  const [params, setParams] = useState(() => ({
    beamSpan: scheme.inputParameters?.beamSpan || 10, // 横梁跨度，单位：米(m)，默认值10m
    windLoadOnPole: scheme.inputParameters?.equivalentWindLoad || 5, // 抱杆所受等效风荷载，单位：千牛(kN)，默认值5kN
    guyWireAngle: scheme.inputParameters?.guylineGroundAngle || 45, // 拉线与地面夹角，单位：度(°)，默认值45°
    poleHeight: scheme.inputParameters?.poleHeight || 15, // 抱杆高度，单位：米(m)，默认值15m
    poleInclinationAngle: scheme.inputParameters?.poleInclinationAngle || 15, // 抱杆倾角，单位：度(°)，默认值15°
    horizontalForceOnPole: scheme.inputParameters?.topHorizontalForce || 20, // 抱杆顶部水平力，单位：千牛(kN)，默认值20kN
  }));

  useEffect(() => {
    const loadSpecs = async () => {
      try {
        setIsLoadingSpecs(true);

        // 修复：增加对实体的存在性检查
        if (!PoleSpecAPI || !AnchorSpecAPI) {
          console.error(
            "PoleSpec 或 AnchorSpec 实体未加载，无法获取规格数据。"
          );
          toast({
            variant: "destructive",
            title: "组件加载错误",
            description: "抱杆或地锚规格组件未能成功加载，请刷新页面重试。",
          });
          setPoleSpecs([]);
          setAnchorSpecs([]);
          return;
        }

        const [poles, anchors] = await Promise.all([
          PoleSpecAPI.getList().catch((error) => {
            console.error("加载抱杆规格失败:", error);
            return [];
          }),
          AnchorSpecAPI.getList().catch((error) => {
            console.error("加载地锚规格失败:", error);
            return [];
          }),
        ]);

        setPoleSpecs(Array.isArray(poles.data) ? poles.data : []);
        setAnchorSpecs(Array.isArray(anchors.data) ? anchors.data : []);
      } catch (error) {
        console.error("加载规格数据失败:", error);
        setPoleSpecs([]);
        setAnchorSpecs([]);
        toast({
          variant: "destructive",
          title: "规格加载失败",
          description: "无法加载抱杆和地锚规格数据，请检查网络连接后重试。",
        });
      } finally {
        setIsLoadingSpecs(false);
      }
    };
    loadSpecs();
  }, [toast]);

  const handleParamChange = (key, value) => {
    setParams((prev) => ({ ...prev, [key]: parseFloat(value) || 0 }));
  };

  const results = useMemo(() => {
    try {
      const totalVerticalLoadOnBeam = autoCalculatedVerticalLoadOnBeam;
      const beamReactionForce = totalVerticalLoadOnBeam / 2;

      const poleInclinationRad = (params.poleInclinationAngle * Math.PI) / 180;
      const guyWireAngleRad = (params.guyWireAngle * Math.PI) / 180;
      const betaRad = (45 * Math.PI) / 180;

      const totalVerticalLoadOnPoleTop = beamReactionForce;
      const totalHorizontalLoadOnPoleTop = params.horizontalForceOnPole;
      const guyWireTension =
        (1.2 * bearingCableMaxTensionKN * Math.cos(betaRad)) /
        (2 * Math.cos(guyWireAngleRad));
      const verticalComponentFromLoad = totalVerticalLoadOnPoleTop;
      const verticalComponentFromGuyWire =
        guyWireTension * Math.sin(guyWireAngleRad);
      const axialCompression =
        (verticalComponentFromLoad + verticalComponentFromGuyWire) /
        Math.cos(poleInclinationRad);
      const maxBendingMoment = totalHorizontalLoadOnPoleTop * params.poleHeight;

      const anchorUpliftForce = guyWireTension * Math.sin(guyWireAngleRad);
      const anchorHorizontalForce = guyWireTension * Math.cos(guyWireAngleRad);

      return {
        beam: {
          reactionForce: beamReactionForce,
          totalLoad: totalVerticalLoadOnBeam,
        },
        pole: { axialCompression, maxBendingMoment, guyWireTension },
        anchor: {
          upliftForce: anchorUpliftForce,
          horizontalForce: anchorHorizontalForce,
          totalTension: guyWireTension,
        },
        error: null,
      };
    } catch (e) {
      return { error: e.message };
    }
  }, [params, autoCalculatedVerticalLoadOnBeam, bearingCableMaxTensionKN]);

  const recommendations = useMemo(() => {
    if (results.error || isLoadingSpecs) return { poles: [], anchors: [] };

    const recommendedPoles = poleSpecs
      .map((spec) => {
        if (
          !spec.materialProperties?.allowableStressMPa ||
          !spec.crossSectionProperties?.sectionModulusCm3 ||
          !spec.crossSectionProperties?.areaCm2
        ) {
          return { ...spec, isOk: false, reason: "规格不完整" };
        }
        const allowableStress = spec.materialProperties.allowableStressMPa;
        const sectionModulus =
          spec.crossSectionProperties.sectionModulusCm3 * 1e-6; // m³
        const area = spec.crossSectionProperties.areaCm2 * 1e-4; // m²
        const bendingStress =
          (results.pole.maxBendingMoment * 1000) / sectionModulus / 1e6; // MPa
        const axialStress = (results.pole.axialCompression * 1000) / area / 1e6; // MPa
        const totalStress = bendingStress + axialStress;
        const isOk = totalStress <= allowableStress;
        return { ...spec, isOk, reason: isOk ? "满足" : `超限` };
      })
      .filter((p) => p.isOk);

    const recommendedAnchors = anchorSpecs.filter(
      (spec) => spec.ratedLoadKN >= results.anchor.totalTension
    );
    return { poles: recommendedPoles, anchors: recommendedAnchors };
  }, [results, poleSpecs, anchorSpecs, isLoadingSpecs]);

  const handleSaveResults = useCallback(() => {
    if (results.error) {
      toast({
        variant: "destructive",
        title: "无法保存",
        description: "计算存在错误。",
      });
      return;
    }
    onUpdate({
      tempStructureResults: {
        ...params,
        ...results,
        calculatedAt: new Date().toISOString(),
      },

      inputParameters: {
        beamSpan: params.beamSpan, //	横梁跨度(m)
        carryingCableMaxTension: bearingCableMaxTensionKN.toFixed(2), //	承载索最大张力(H)
        equivalentWindLoad: params.windLoadOnPole, //		等效风荷载(kN)
        guylineGroundAngle: params.guyWireAngle, //	拉线与地面夹角(°)
        poleHeight: params.poleHeight, //		抱杆高度(m)
        poleInclinationAngle: params.poleInclinationAngle, //		抱杆倾角(°)
        topHorizontalForce: params.horizontalForceOnPole, //		顶部水平力(kN)
      },

      calculationResults: {
        axialPressure: results.pole?.axialCompression?.toFixed(2), //	轴向压力(kN)
        guylineTension: results.pole?.guyWireTension?.toFixed(2), //	拉线张力(kN)
        horizontalForce: results.anchor?.horizontalForce?.toFixed(2), //水平力(kN)
        maxBendingMoment: results.pole?.maxBendingMoment?.toFixed(2), //最大弯矩(kN·m)
        singleSupportReaction: results.beam?.reactionForce?.toFixed(2), //	单侧支座反力(kN)
        totalVerticalLoad: results.beam?.totalLoad?.toFixed(2), //总垂直荷载(kN)
        upliftForce: results.anchor?.upliftForce?.toFixed(2), //上拔力(kN)
      },
    });
    toast({ title: "保存成功", description: "临时装置受力分析结果已更新。" });
  }, [results, params, onUpdate, toast]);
  const formulas = [
    {
      name: "临时装置总荷载",
      description: "临时装置（跨越架、承载索等）受到的总荷载",
      formula: "FTotal = √(FV² + FH²)",
      variables: [
        { symbol: "FTotal", description: "总荷载", unit: "kN" },
        { symbol: "FV", description: "最大垂直荷载", unit: "kN" },
        { symbol: "FH", description: "最大水平荷载", unit: "kN" },
      ],
      conditions: [
        "采用矢量合成计算总荷载",
        "垂直荷载主要来自承载索、导线、封网装置自重",
        "水平荷载主要来自牵引张力、风荷载",
      ],
    },
    {
      name: "单个地锚承受荷载",
      description: "假设地锚均匀分担总荷载",
      formula: "FAnchorSingle = FTotal / NAnchor",
      variables: [
        {
          symbol: "FAnchorSingle",
          description: "单个地锚承受荷载",
          unit: "kN",
        },
        { symbol: "FTotal", description: "总荷载", unit: "kN" },
        { symbol: "NAnchor", description: "地锚数量", unit: "个" },
      ],
      conditions: [
        "假设荷载均匀分配到各地锚",
        "实际受力需考虑布置角度和位置",
        "不均匀受力时应进行详细力学分析",
      ],
    },
    {
      name: "地锚所需承载力",
      description: "考虑安全系数后地锚需满足的承载力",
      formula: "FAnchorRated = FAnchorSingle × KSafety",
      variables: [
        { symbol: "FAnchorRated", description: "地锚额定承载力", unit: "kN" },
        {
          symbol: "FAnchorSingle",
          description: "单个地锚承受荷载",
          unit: "kN",
        },
        { symbol: "KSafety", description: "安全系数", unit: "-" },
      ],
      conditions: [
        "安全系数一般取2.5",
        "需考虑土质条件对地锚承载力的影响",
        "不同类型地锚（螺旋、混凝土、岩石锚杆）的安全系数要求不同",
      ],
      reference: "DL/T 5285-2013 输电线路工程施工安全规程",
    },
    {
      name: "拉线绳所需破断力",
      description: "支撑临时装置的拉线绳破断力要求",
      formula: "FGuyRope = FAnchorRated",
      variables: [
        { symbol: "FGuyRope", description: "拉线绳破断力", unit: "kN" },
        { symbol: "FAnchorRated", description: "地锚额定承载力", unit: "kN" },
      ],
      conditions: [
        "拉线绳破断力应不小于地锚承载力",
        "需考虑拉线绳的连接强度",
        "钢丝绳和合成纤维绳的选择需根据具体工况",
      ],
    },
  ];
  if (!scheme)
    return (
      <Alert variant="destructive">
        <AlertTriangle className="h-4 w-4" />
        <AlertTitle>错误</AlertTitle>
        <AlertDescription>无法加载方案数据。</AlertDescription>
      </Alert>
    );

  return (
    <TooltipProvider>
      <FormulaDisplay
        standard="DL/T 5301-2013 输电线路工程架线施工工艺规程"
        formulas={formulas}
      />

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mt-6">
        {/* 左侧栏: 输入参数 */}
        <div className="space-y-4">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-lg flex items-center gap-2">
                <Combine className="w-4 h-4 text-blue-600" />
                输入参数
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="p-2 bg-slate-50 rounded border">
                <Label className="text-xs">承载索最大张力 (H)</Label>
                <Input
                  value={
                    bearingCableMaxTensionKN > 0
                      ? `${bearingCableMaxTensionKN.toFixed(2)} kN`
                      : "承载索参数缺失"
                  }
                  readOnly
                  className="h-8 mt-1 bg-slate-100 cursor-not-allowed"
                />
              </div>
              <div className="space-y-3">
                <h4 className="text-sm font-medium flex items-center gap-2">
                  <MoveRight className="w-4 h-4" />
                  横梁参数
                </h4>
                <div className="grid grid-cols-2 gap-2">
                  <div>
                    <Label className="text-xs">横梁跨度 (m)</Label>
                    <Input
                      id="beamSpan"
                      type="number"
                      value={params.beamSpan}
                      onChange={(e) =>
                        handleParamChange("beamSpan", e.target.value)
                      }
                      className="h-8 mt-1"
                    />
                  </div>
                </div>
              </div>
              <div className="space-y-3">
                <h4 className="text-sm font-medium flex items-center gap-2">
                  <Pilcrow className="w-4 h-4" />
                  抱杆与拉线参数
                </h4>
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
                  <div>
                    <Label className="text-xs">抱杆高度 (m)</Label>
                    <Input
                      id="poleHeight"
                      type="number"
                      value={params.poleHeight}
                      onChange={(e) =>
                        handleParamChange("poleHeight", e.target.value)
                      }
                      className="h-8 mt-1"
                    />
                  </div>
                  <div>
                    <Label className="text-xs">抱杆倾角 (°)</Label>
                    <Input
                      id="poleInclinationAngle"
                      type="number"
                      value={params.poleInclinationAngle}
                      onChange={(e) =>
                        handleParamChange(
                          "poleInclinationAngle",
                          e.target.value
                        )
                      }
                      className="h-8 mt-1"
                    />
                  </div>
                  <div>
                    <Label className="text-xs">顶部水平力 (kN)</Label>
                    <Input
                      id="horizontalForceOnPole"
                      type="number"
                      value={params.horizontalForceOnPole}
                      onChange={(e) =>
                        handleParamChange(
                          "horizontalForceOnPole",
                          e.target.value
                        )
                      }
                      className="h-8 mt-1"
                    />
                  </div>
                  <div>
                    <Label className="text-xs">等效风荷载 (kN)</Label>
                    <Input
                      id="windLoadOnPole"
                      type="number"
                      value={params.windLoadOnPole}
                      onChange={(e) =>
                        handleParamChange("windLoadOnPole", e.target.value)
                      }
                      className="h-8 mt-1"
                    />
                  </div>
                  <div>
                    <Label className="text-xs">拉线与地面夹角 (°)</Label>
                    <Input
                      id="guyWireAngle"
                      type="number"
                      value={params.guyWireAngle}
                      onChange={(e) =>
                        handleParamChange("guyWireAngle", e.target.value)
                      }
                      className="h-8 mt-1"
                    />
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 右侧栏: 计算结果 */}
        <div className="space-y-4">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-lg flex items-center gap-2">
                <Calculator className="w-4 h-4 text-purple-600" />
                计算结果
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <h4 className="text-sm font-medium">横梁</h4>
                <div className="grid grid-cols-2 gap-2 text-center">
                  <div className="p-2 bg-slate-50 rounded border">
                    <div className="text-xs text-gray-500">总垂直荷载</div>
                    <div className="font-bold">
                      {results.beam?.totalLoad?.toFixed(2) ?? "N/A"} kN
                    </div>
                  </div>
                  <div className="p-2 bg-slate-50 rounded border">
                    <div className="text-xs text-gray-500">单侧支座反力</div>
                    <div className="font-bold">
                      {results.beam?.reactionForce?.toFixed(2) ?? "N/A"} kN
                    </div>
                  </div>
                </div>
              </div>
              <div className="space-y-2">
                <h4 className="text-sm font-medium">抱杆</h4>
                <div className="grid grid-cols-3 gap-2 text-center">
                  <div className="p-2 bg-blue-50 rounded border">
                    <div className="text-xs text-blue-600">拉线张力</div>
                    <div className="font-bold text-blue-800">
                      {results.pole?.guyWireTension?.toFixed(2) ?? "N/A"} kN
                    </div>
                  </div>
                  <div className="p-2 bg-slate-50 rounded border">
                    <div className="text-xs text-gray-500">轴向压力</div>
                    <div className="font-bold">
                      {results.pole?.axialCompression?.toFixed(2) ?? "N/A"} kN
                    </div>
                  </div>
                  <div className="p-2 bg-slate-50 rounded border">
                    <div className="text-xs text-gray-500">最大弯矩</div>
                    <div className="font-bold">
                      {results.pole?.maxBendingMoment?.toFixed(2) ?? "N/A"} kN·m
                    </div>
                  </div>
                </div>
              </div>
              <div className="space-y-2">
                <h4 className="text-sm font-medium">地锚</h4>
                <div className="grid grid-cols-2 gap-2 text-center">
                  <div className="p-2 bg-slate-50 rounded border">
                    <div className="text-xs text-gray-500">上拔力</div>
                    <div className="font-bold">
                      {results.anchor?.upliftForce?.toFixed(2) ?? "N/A"} kN
                    </div>
                  </div>
                  <div className="p-2 bg-slate-50 rounded border">
                    <div className="text-xs text-gray-500">水平力</div>
                    <div className="font-bold">
                      {results.anchor?.horizontalForce?.toFixed(2) ?? "N/A"} kN
                    </div>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-lg flex items-center gap-2">
                <Boxes className="w-4 h-4 text-green-700" />
                推荐选型
              </CardTitle>
            </CardHeader>
            <CardContent>
              {isLoadingSpecs ? (
                <div className="flex items-center justify-center p-4">
                  <Loader2 className="w-6 h-6 animate-spin" />
                </div>
              ) : (
                <div className="space-y-4">
                  <div>
                    <h4 className="font-medium text-sm mb-2">抱杆</h4>
                    {recommendations.poles.length > 0 ? (
                      <div className="border rounded max-h-32 overflow-y-auto">
                        <Table>
                          <TableHeader>
                            <TableRow className="text-xs">
                              <TableHead>型号</TableHead>
                              <TableHead>材料</TableHead>
                              <TableHead>许用应力(MPa)</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {recommendations.poles.map((p) => (
                              <TableRow key={p.id} className="text-xs">
                                <TableCell>{p.model}</TableCell>
                                <TableCell>{p.material}</TableCell>
                                <TableCell>
                                  {p.materialProperties?.allowableStressMPa}
                                </TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      </div>
                    ) : (
                      <p className="text-xs text-gray-500 p-2 bg-gray-50 rounded">
                        无合适抱杆规格。
                      </p>
                    )}
                  </div>
                  <div>
                    <h4 className="font-medium text-sm mb-2">地锚</h4>
                    {recommendations.anchors.length > 0 ? (
                      <div className="border rounded max-h-32 overflow-y-auto">
                        <Table>
                          <TableHeader>
                            <TableRow className="text-xs">
                              <TableHead>型号</TableHead>
                              <TableHead>类型</TableHead>
                              <TableHead>额定载荷(kN)</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {recommendations.anchors.map((a) => (
                              <TableRow key={a.id} className="text-xs">
                                <TableCell>{a.model}</TableCell>
                                <TableCell>{a.type}</TableCell>
                                <TableCell>{a.ratedLoadKN}</TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      </div>
                    ) : (
                      <p className="text-xs text-gray-500 p-2 bg-gray-50 rounded">
                        无合适地锚规格。
                      </p>
                    )}
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
          <div className="flex justify-end">
            <Button onClick={handleSaveResults} className="w-full lg:w-auto">
              <Save className="w-4 h-4 mr-2" />
              保存结果
            </Button>
          </div>
        </div>
      </div>
    </TooltipProvider>
  );
}
